package protocol.common.httpclient.response;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.http.ParseException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

/**
 * HttpResponseDefaultHandler 工具类
 * 默认的响应处理类
 *
 * @author 陈杰
 * @version 1.0
 * @since 2016年3月3日 00:18:48
 *
 * Copyright (c) 2016 陈杰(chenjie_java@aliyun.com)
 */
public class HttpResponseDefaultHandler {
	private CloseableHttpResponse httpResponse;
	
	/**
	 * 创建默认的响应处理类
	 * */
	public static HttpResponseDefaultHandler createResponseHandler(CloseableHttpResponse httpResponse){
		HttpResponseDefaultHandler reponseHandler = new HttpResponseDefaultHandler();
		reponseHandler.httpResponse = httpResponse;
		return reponseHandler;
	}
	
	/**
	 * 获取响应对象的String格式
	 * */
	public String getResponseString() throws ParseException, IOException{
		return URLDecoder.decode(EntityUtils.toString(httpResponse.getEntity()),"utf-8");
	}
	
	/**
	 * 获取响应对象流
	 * */
	public InputStream getResponseSteam() throws ParseException, IOException{
		return httpResponse.getEntity().getContent();
	}
	
	/**
	 * 
	 * 检查请求状态，如果不正常则抛出异常
	 * */
	public void checkRequestStatus() throws IOException{
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		if (statusCode < 200 || statusCode >= 300){
			throw new IOException("status is error");
		}
	}
	
	/**
	 * 获取请求状态码
	 * */
	public int getRequestStatus(){
		return httpResponse.getStatusLine().getStatusCode();
	}
}
